package com.tanqidi.arcgisandroid.ui.layerConfig.subLayer.metadata

import android.content.Context
import android.os.Bundle
import android.text.TextUtils
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.AutoCompleteTextView
import android.widget.LinearLayout
import androidx.activity.OnBackPressedDispatcher
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import com.google.android.material.textfield.TextInputEditText
import com.tanqidi.arcgisandroid.R
import com.tanqidi.arcgisandroid.base.BaseRecyclerAdapter
import com.tanqidi.arcgisandroid.base.RecyclerViewHolder
import com.tanqidi.arcgisandroid.data.layerConfig.Field
import com.tanqidi.arcgisandroid.data.layerConfig.LayerConfig
import com.tanqidi.arcgisandroid.data.project.Project
import com.tanqidi.arcgisandroid.databinding.FragmentMetadataBinding
import com.tanqidi.arcgisandroid.databinding.ItemMetadataItemBinding
import com.tanqidi.arcgisandroid.ui.layerConfig.subLayer.fieldConfig.FieldConfigViewModel
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class MetadataFragment : Fragment() {

    private val fieldConfigViewModel by viewModels<FieldConfigViewModel>()
    private lateinit var binding: FragmentMetadataBinding
    private lateinit var adapter: MetadataAdapter

    private val args by navArgs<MetadataFragmentArgs>()
    //从本地读取出来的layer对象
    private lateinit var layer: LayerConfig
    private lateinit var project: Project

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = FragmentMetadataBinding.inflate(layoutInflater)

        //读取出来project
        project = fieldConfigViewModel.getProjectByName(args.projectName)
        //project有了然后再从project中拿到layer对象
        layer = project.layers.filter { it.name == args.layerName }[0]
    }

    override fun onPause() {
        super.onPause()
        save()
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        initTopBar()
        initViewEvent()
        initRecycleView()
        return binding.root
    }

    private fun initViewEvent() {

    }

    private fun initRecycleView() {
        val recyclerView = binding.recyclerView
        adapter = MetadataAdapter(requireContext(), layer.fields.filter { it.metadataList.isNotEmpty() })
        recyclerView.adapter = adapter
    }

    private fun initTopBar(){
        binding.topAppBar.apply {
            setNavigationOnClickListener { findNavController().navigateUp() }
            setOnMenuItemClickListener {
                when (it.itemId) {
                    R.id.add -> {
                        adapter.add(Field())
                    }
                    R.id.save -> {
                        save()
                    }
                }
                true
            }
        }
    }

    private inner class MetadataAdapter(context: Context, list:List<Field>?) : BaseRecyclerAdapter<Field>(context, list) {
        override fun getItemLayoutId(viewType: Int): Int {
            return R.layout.item_metadata
        }
        override fun bindData(holder: RecyclerViewHolder, position: Int, item: Field) {
            (holder.getView(R.id.alias) as TextInputEditText).apply {
                setText(item.alias)
                addTextChangedListener {
                    val content = it.toString().trim()
                    if (!TextUtils.isEmpty(content)) {
                        item.alias = content
                    }
                }
            }
            (holder.getView(R.id.field) as TextInputEditText).apply {
                setText(item.field)
                addTextChangedListener {
                    val content = it.toString().trim()
                    if (!TextUtils.isEmpty(content)) {
                        item.field = content
                    }
                }
            }


            val view = holder.getView(R.id.container) as LinearLayout
            item.metadataList.forEachIndexed { index, metadataField ->
                addMetadataItem(view, metadataField, item)
            }
            holder.getView(R.id.add).setOnClickListener {
                val metadataField = Field()
                item.metadataList.add(metadataField)
                addMetadataItem(view, metadataField, item)
            }
        }
    }

    private fun addMetadataItem(view: LinearLayout, metadataField: Field, field: Field) : ItemMetadataItemBinding {
        //子元素
        val itemMetadataItemBinding = ItemMetadataItemBinding.inflate(layoutInflater, view, true).apply {
            name.apply {
                setText(metadataField.alias)
                addTextChangedListener {
                    metadataField.alias = it.toString().trim()
                }
            }
            value.apply {
                setText(metadataField.defaultValue)
                addTextChangedListener {
                    metadataField.defaultValue = it.toString().trim()
                }
            }
            delete.setOnClickListener {
                field.metadataList.remove(metadataField)

                view.removeView(this.root)
            }
        }
        return itemMetadataItemBinding
    }

    private fun save(){
        //在返回页面的时候，重新保存project到本地
        layer.fields.removeAll(layer.fields.filter { it.metadataList.isNotEmpty() })
        adapter.data.forEach {
            layer.fields.add(0, it)
        }
        fieldConfigViewModel.saveProject(project)
    }
}